<?php
namespace app\api\model;
use think\Model;

class Category extends Model{
    protected $type = [
        'id'    =>  'integer',     
        'parent_id'=>'integer'
    ];
    public function parent(){
        return $this->hasOne('Category','id','parent_id')->bind(['parent_name'=>'title']);
    }

    public function categoryList($filter = null){
        $where = [];
        $page = 1;
        $pageCount = 10;       
        if(!empty($filter)){
            //指定id查询
            if(!empty($filter['id'])){
                $where['id'] = $filter['id'];
            }
            //模糊查询           
            if(!empty($filter['keyword'])){
                $where['title'] = ['like',"%{$filter['keyword']}%"];               
            }
            if(!empty($filter['parent_id'])){
                $where['parent_id'] = ['=',$filter['parent_id']];
            }else{
                $where['parent_id'] = ['>',0];
            }
            //页码            
            $page = !empty($filter['page']) ? $filter['page'] : $page;
            $pageCount = !empty($filter['page_count']) ? $filter['page_count'] : $pageCount;
        }
        $datas = $this->where($where)->page("$page,$pageCount")->order('id', 'desc')->select();
        $dataCount =  $this->where($where)->count();       
        $datalist = array(
            'datas' => $datas,           
            'dataCount' => $dataCount
        );
        return $datalist;
    }
}